package com.wmjsoft.plugins.nutzplugin.dao

import org.nutz.dao.Chain
import org.nutz.dao.Cnd
import org.nutz.dao.FieldFilter
import org.nutz.dao.FieldMatcher

class Inserter(private var mySql:QueerSql) {


    // 修改或修改是否默认忽略空值
    private var updateOrInsertIgnoreNull = true

    private var actived: StringBuilder? = null // 需要保留的字段


    private var locked: StringBuilder? = null // 需要忽略的字段


    fun init(mySql: QueerSql): Inserter {
        this.mySql = mySql
        builder()
        return this
    }


    private fun builder(): Inserter {
        actived = StringBuilder("^")
        locked = StringBuilder("^")
        return this
    }

    private fun build(): Inserter {
        if (actived != null && actived!!.length > 1) {
            val start = actived!!.lastIndexOf("|")
            actived!!.replace(start, start + 1, "$")
        } else {
            actived = null
        }
        if (locked != null && locked!!.length > 1) {
            val start = locked!!.lastIndexOf("|")
            locked!!.replace(start, start + 1, "$")
        } else {
            locked = null
        }
        return this
    }

    fun act(vararg actived: String?): Inserter {
        for (str in actived) {
            this.actived!!.append(str).append("|")
        }
        return this
    }

    fun loc(vararg locked: String?): Inserter {
        for (str in locked) {
            this.locked!!.append(str).append("|")
        }
        return this
    }

    fun igNull(): Inserter {
        updateOrInsertIgnoreNull = !updateOrInsertIgnoreNull
        return this
    }


    fun <T> insert(t: T): T {
        this.build()
        val act = if (actived == null) null else actived.toString()
        val loc = if (locked == null) null else locked.toString()
        return mySql.dao
            .insert(
                t,
                FieldFilter.create(
                    t!!::class.java,
                    act,
                    loc,
                    updateOrInsertIgnoreNull
                )
            )
    }


    fun <T, D> updateById(t: T, id: D): Int {
        this.build()
        val act = if (actived == null) null else actived.toString()
        val loc = if (locked == null) null else locked.toString()
        val fieldMatcher = FieldMatcher.make(
            act, loc,
            updateOrInsertIgnoreNull
        )
        return mySql.dao.update(mySql.clazz, Chain.from(t, fieldMatcher), Cnd.where("id", "=", id))
    }
}